package hotLeetcode;

public class H64Leetcode {
    public int minPathSum1(int[][] grid) {
        //定义dp  [] 还是 [][]
        //分析只能向下或者向右  不管 先来个[][] 好理解  dp[i][j]  = (i,j) 位置前的路径最小和
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m][n];
        //转移方程
        //  dp[i][j] = min(dp[i-1][j] , dp[i][j-1] ) + grid[i][j];

        dp[0][0] = grid[0][0];
        //初始化dp[][]
        for (int i = 1; i < m; i++) {  // 初始化第一列
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }

        for (int j = 1; j < n; j++) {
            dp[0][j] = dp[0][j - 1] + grid[0][j];  // 初始化第一行

        }


        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }

        return dp[m - 1][n - 1];
    }



    //使用一维数组优化
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[] dp = new int[n];

        //初始化
        dp[0] = grid[0][0];

        //初始化第一行
        for (int i = 1; i < n; i++) {
            dp[i] = dp[i - 1] + grid[0][i];
        }

        for (int i = 1; i < m; i++) {
            dp[0] += grid[i][0];
            for (int j = 1; j < n; j++) {

                dp[j] = Math.min(dp[j], dp[j - 1]) + grid[i][j];

            }
        }


        return dp[n - 1];


    }



}
